/**
 * 处理所有以/user/*开头请求的路由器
 */
const express = require("express");
const pool = require("../pool");
let router = express.Router();
module.exports = router;

/**
 * 1.1	用户注册
	接口URL
		{{url}}/user/register
	请求方式
		POST
	请求 Content-Type
		application/json
	请求Body参数
		uname	zhangsan	必填	-用户名
		upwd	123456	必填	-密码
		phone	13333333333	必填	-手机号
		captcha	ad31	必填	-验证码
	成功响应示例
	{
		"code": 200,
		"msg": "register success",
		"uid": 7
	}
 */
router.post("/register", (req, res, next) => {
  //读取请求数据
  let uname = req.body.uname;
  if (!uname) {
    //验证客户端请求中是否提交了用户名
    let output = {
      code: 401,
      msg: "uname required",
    };
    res.json(output);
    return;
  }
  let upwd = req.body.upwd;
  if (!upwd) {
    //验证客户端请求中是否提交了密码
    let output = {
      code: 402,
      msg: "upwd required",
    };
    res.json(output);
    return;
  }
  let phone = req.body.phone;
  if (!phone) {
    //验证客户端请求中是否提交了电话号码
    let output = {
      code: 403,
      msg: "phone required",
    };
    res.json(output);
    return;
  }
  let captcha = req.body.captcha;
  if (!captcha) {
    //客户端未提交验证码
		let output = {
			code: 409,
			msg:"captcha required"
		};
    res.send(output);
    return;
  }
  if (captcha.toLowerCase() !== req.session.registerCaptcha) {
		//客户端提交的验证码有误
		let output = {
			code: 410,
			msg :"captcha error"
		}
    res.send(output);
    return;
  } else {
    delete req.session.registerCaptcha; //验证通过，销毁会话中此次使用过的验证码
  }
  //TODO: 此处省略了邮箱和电话的格式验证

  //执行数据库验证——用户名(及邮箱)和电话是否已经存在
  let sql = "SELECT uid FROM user WHERE uname=?  OR  phone=?";
  pool.query(sql, [uname, phone], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.length > 0) {
      //根据客户端提交的用户名和电话查到了相关记录
      let output = {
        code: 409,
        msg: "uname or phone already taken", //用户名或电话已被占用
      };
      res.json(output);
      return;
    }
    //用户名和密码均未被占用，开始执行数据库添加操作
    let sql = "INSERT INTO user(uname,upwd,phone) VALUES(?,?,?)";
    pool.query(sql, [uname, upwd, phone], (err, result) => {
      if (err) {
        next(err);
        return;
      }
      //INSERT语句执行成功，输出注册成功的响应消息
      let output = {
        code: 200,
        msg: "regisgter success",
        uid: result.insertId, //INSERT语句产生的自增编号就是新用户编号
      };
      res.json(output);
      //Cannot set headers after  they are sent to the client——Express经典错误！！
      //res.send/json方法都会发生一个完整的响应消息:  起始行 / 响应头部 / 主体,
      //res.json({})
      //res.json({})
    });
  });
});

/**
 * 1.2	用户登录
	接口URL
		{{url}}/user/login
	请求方式
		POST
	请求 Content-Type
		application/json
	请求Body参数
		uname	lisi	必填	-用户名
		upwd	abc123	必填	-密码
	成功响应示例
	{
		"code": 200,
		"msg": "login success",
		"sessionUser": {
			"uid": 5,
			"uname": "ranran@tedu.cn",
			"nickname": "然然"    
		}
	}
 */
router.post("/login", (req, res, next) => {
  //获取客户端提交的请求数据
  let uname = req.body.uname;
  if (!uname) {
    //验证客户端提交的uname
    let output = {
      code: 401,
      msg: "uname required",
    };
    res.json(output);
    return;
  }
  let upwd = req.body.upwd;
  if (!upwd) {
    //验证客户端提交的upwd
    let output = {
      code: 402,
      msg: "upwd required",
    };
    res.json(output);
    return;
  }

  //执行数据库查询操作
  let sql = "SELECT uid,uname FROM user WHERE uname=? AND upwd=?";
  pool.query(sql, [uname, upwd], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.length === 0) {
      //指定用户名和密码的用户没有查询到
      let output = {
        code: 400,
        msg: "uname or upwd error",
      };
      res.json(output);
    } else {
      //指定用户名和密码的用户查询到了
      //在当前服务器端会话中记录登录用户信息
      req.session.user = result[0]; //{uid:2, uname:'xxx', nickname:'yyy'}
      req.session.save(); //保存会话数据
      //向客户端输出响应消息，提示登录成功
      let output = {
        code: 200,
        msg: "login success",
        sessionUser: req.session.user,
      };
      res.json(output);
    }
  });
});

/**
 * 1.3	检测用户名是否存在
 *	接口URL
 *		{{url}}/user/check_uname
 *	请求方式
 *		GET
 *	请求查询字符串参数
 *		uname	zhangsan	必填	-用户名
 *	成功响应示例
 *	{
 *		"code": 200,
 *		"msg": "exists"
 *	}
 *	失败响应示例
 *	{
 *		"code": 401,
 *		"msg": "non-exists"
 *	}
 */
router.get("/check_uname", (req, res, next) => {
  //读取请求数据
  let uname = req.query.uname;
  if (!uname) {
    let output = {
      code: 400,
      msg: "uname required",
    };
    res.json(output);
    return;
  }
  //执行数据库查询
  let sql = "SELECT uid FROM user WHERE uname=?";
  pool.query(sql, uname, (err, result) => {
    if (err) {
      //throw  err    //开发/测试阶段可以使用，上线运行时期不允许使用
      next(err); //终止当前方法的执行，调用Express后置的错误中间件，处理异步错误
      return;
    }
    //SQL语句执行成功，输出响应消息
    if (result.length > 0) {
      //查询结果集中有数据——可以根据uname查询到一个uid
      let output = {
        code: 200,
        msg: "uname exists",
      };
      res.json(output);
    } else {
      let output = {
        code: 401,
        msg: "uname not exists",
      };
      res.json(output);
    }
  });
});

/**
 * 1.4	检测手机号是否存在
	接口URL
		{{url}}/user/check_phone
	请求方式
		GET
	请求查询字符串参数
		phone	13333333333	必填	-手机号
	成功响应示例
	{
		"code": 200,
		"msg": "phone exists"
	}
	失败响应示例
	{
		"code": 402,
		"msg": "phone non-exists"
	}
 */
router.get("/check_phone", (req, res, next) => {
  //读取请求数据
  let phone = req.query.phone;
  if (!phone) {
    let output = {
      code: 401,
      msg: "phone required",
    };
    res.json(output);
    return;
  }
  //执行数据库查询
  let sql = "SELECT uid FROM user WHERE phone=?";
  pool.query(sql, phone, (err, result) => {
    if (err) {
      next(err);
      return;
    }
    //SQL语句执行成功，输出响应消息
    if (result.length > 0) {
      //查询结果集中有数据
      let output = {
        code: 200,
        msg: "phone exists",
      };
      res.json(output);
    } else {
      let output = {
        code: 402,
        msg: "phone not exists",
      };
      res.json(output);
    }
  });
});
